package com.dsjy.yf.address.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author whj
 * @version 1.0
 * @date 2021-01-28 9:04
 */
@Slf4j
public class FileUtil {
    private static final String LINE_SEPARATOR = "\r\n";
    private static final String SEPARATION = "%&#";
    private static final String CSV_SUFFIX = ".csv";
    /**
     * 上传文件的存储位置
     */
    //public final static String TEM_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "tem/";
    public final static String TEM_PATH = "D:/projects/address/tem/";

    /**
     * 根据路径创建文件夹
     *
     * @param path
     * @return
     */
    public static File creatFileDir(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        return file;
    }

    public static boolean creatSubFile(List<String> list, String pathName) throws IOException {
        Path path = Paths.get(pathName);
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
            for (String item : list) {
                writer.write(item + LINE_SEPARATOR);
            }
            writer.flush();
            return true;
        }
    }

    /**
     * 创建预返回的CSV文件
     *
     * @param pathName
     * @return
     * @throws IOException
     */
    public static String creatModelCSVfile(String pathName) throws IOException {
        List<String> str = getCSVHeaders();
        Path path = Paths.get(pathName);
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
            for (String item : str) {
                writer.write(item + LINE_SEPARATOR);
            }
            writer.flush();
            return pathName;
        }
    }

    /**
     * 获取已拆分的子文件
     *
     * @param pathName
     * @return
     */
    public static List<String> getAddressList(String pathName) {
        Path path = Paths.get(pathName + CSV_SUFFIX);
        String str = null;
        List<String> addressList = null;
        try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            addressList = new ArrayList<>();
            while ((str = reader.readLine()) != null) {
                addressList.add(str);
            }
            return addressList;
        } catch (Exception e) {
            log.error("获取文件" + pathName + "时发生错误" + " ===> " + e.getMessage());
            return null;
        }
    }

    /**
     * 拆分CSV大文件
     *
     * @param filePath
     * @param file
     * @return
     */
    public static Integer splitCSVFile(String filePath, File file) {
        BufferedReader bufferedReader = null;
        InputStreamReader inputStreamReader = null;
        FileInputStream fileInputStream = null;
        String str = null;
        String[] strArray = null;
        String id = null;
        String value = null;
        List<String> list = new ArrayList<>(200000);
        try {
            if (file == null) {
                return null;
            }
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream, "GBK");
            bufferedReader = new BufferedReader(inputStreamReader);
            int num = 0;
            log.info("first line:" + bufferedReader.readLine());
            while ((str = bufferedReader.readLine()) != null) {
                strArray = str.split(",");
                if (strArray.length < 2) {
                    continue;
                }
                id = MyStringUtil.emptyToNull(strArray[0]);
                value = MyStringUtil.removeSign(strArray[1]);
                if (id == null || value == null) {
                    continue;
                }
                list.add(id + SEPARATION + value);
                if (list.size() == 200000) {
                    creatSubFile(list, filePath + (++num) + CSV_SUFFIX);
                    list.clear();
                }
            }
            if (list.size() > 0) {
                creatSubFile(list, filePath + (++num) + CSV_SUFFIX);
                list = null;
            }
            return num;
        } catch (IOException e) {
            log.error("拆分CSV文件失败" + e.getMessage(), e);
            return null;
        } finally {
            //关闭流
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param filePath
     */
    public static void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File item : files) {
                    item.delete();
                }
            }
            file.delete();
        }
        log.info("文件删除完毕:" + filePath);
    }

    private static List<String> getCSVHeaders() throws IOException {
        List<String> str = null;
        Workbook workbook = null;
        try {
            workbook = DownLoadUtil.getModelWorkboolWithRead();
            Sheet sheet = workbook.getSheetAt(0);
            str = new ArrayList<>();
            str.add(getHeaderLine(sheet.getRow(0)));
            str.add(getHeaderLine(sheet.getRow(1)));
        } finally {
            if (workbook != null) {
                workbook.close();
            }
        }
        return str;
    }

    private static String getHeaderLine(Row row) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < row.getLastCellNum(); i++) {
            stringBuilder.append(row.getCell(i).getStringCellValue()).append(",");
        }
        return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
    }


}
